package net.woggle.shackbrowseapi;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.*;


import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;

import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;


@SuppressWarnings("serial")
public class Search extends HttpServlet {
	
	class SearchResult
	{
		String author;
		String date;
		String text;
		String postId;
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		
		resp.setContentType("application/json; charset=UTF-8");
		
		String terms = req.getParameter("terms");
		String author = req.getParameter("author");
		String parentAuthor = req.getParameter("parentAuthor");
		String category = req.getParameter("category");
		String page = req.getParameter("page");
		
		if (category == null)
			category = "all";
		if (terms == null)
			terms = "";
		if (parentAuthor == null)
			parentAuthor = "";
		if (author == null)
			author = "";
		if (page == null)
			page = "1";
		
		Document doc = Jsoup.connect("http://www.shacknews.com/search?chatty=1&type=4&chatty_term=" + URLEncoder.encode(terms, "UTF8") + "&chatty_user=" + URLEncoder.encode(author, "UTF8") + "&chatty_filter=" + URLEncoder.encode(category, "UTF8") + "&result_sort=postdate_desc&page=" + URLEncoder.encode(page, "UTF8") + "&chatty_author=" + URLEncoder.encode(parentAuthor, "UTF8")).get();
		
		Elements users = doc.select("li.result");
		
		JSONArray comments = new JSONArray();
		for (Element thisEl : users)
		{
			SearchResult res = new SearchResult();
			res.author = thisEl.getElementsByClass("chatty-author").get(0).child(0).ownText().replace(":", "");
			res.date = thisEl.getElementsByClass("postdate").get(0).ownText().substring(7);
			res.text = Parser.unescapeEntities(thisEl.getElementsByAttributeValueStarting("href", "/chatty/").get(0).ownText(), true);
			String href = thisEl.getElementsByAttributeValueStarting("href", "/chatty/").get(0).attributes().get("href");
			String prefix = "/chatty/";
			res.postId = href.substring(prefix.length());
			
			JSONObject result = new JSONObject();
			
			try {
				result.put("id", res.postId);
				result.put("author", res.author);
				result.put("date", res.date);
				result.put("preview", res.text);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			comments.put(result);
		}
		JSONObject container = new JSONObject();
		try {
			container.put("comments", comments);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resp.getWriter().print(container.toString());
	}
}
